// pages/shoppingCart/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        openId: "",
        cart: [],
        PSId: [],
        activityList: [],
        allChecked: false,
        userType: 0,
        price: 0,
        discount: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const openId = wx.getStorageSync('openId')
        wx.request({
            url: 'https://mbp.jyccloud.cn/mbp/getCartList',
            method: 'post',
            data: JSON.stringify({
                openId: openId
            }),
            success: (res2) => {
                wx.setStorageSync("cart", res2.data)
                const cart = res2.data
                const userType = parseInt(wx.getStorageSync('userType'))
                const formatCart = cart["cartList"] ? cart["cartList"].map(r => {
                    const item = {}
                    item["count"] = r.count
                    cart["productList"].forEach(r1 => {
                        if (r1.productId === r.productId) {
                            item["productId"] = r1.productId
                            item["title"] = r1.name
                            item["imageUrl"] = r1.imageUrl
                        }
                    })
                    cart["specList"].forEach(r2 => {
                        if (r2.specId === r.specId) {
                            item["specId"] = r2.specId
                            item["specName"] = r2.specName
                            item["price"] = r2.price
                            item["tradePrice"] = r2.tradePrice
                        }
                    })
                    return item
                }) : []

                const activityList = cart["activityList"] ? cart["activityList"].map(r => {
                    const item = {}
                    item["activityType"] = r.activityType
                    item["contrastType"] = r.contrastType
                    item["contrastId"] = r.contrastId
                    item["minPrice"] = r.minPrice
                    item["activity"] = r.activity
                    item["activityMsg"] = r.activityType === "满减" ? "满" + r.minPrice + "减" + r.activity : r.activityType === "买赠" ? "买" + r.minPrice + "赠" + r.activity : r.activityType === "折扣" ? r.minPrice !== 0 ? "满" + r.minPrice + "元" + r.activity + "折" : r.activity + "折" : ""
                    cart["productList"].forEach(r1 => {
                        if (r.contrastType === "商品" && r.contrastId === r1.productId) {
                            item["name"] = r1.name
                        }
                        // else if(r.contrastType==="分类"){
                        //   item["name"]=wx.getStorageSync("productType").filter(item=>item.typeId===r.contrastId)[0]["typeName"]
                        // }
                    })
                    return item
                }) : []

                this.setData({
                    openId: openId,
                    price: 0,
                    PSId: [],
                    discount: 0,
                    cart: formatCart,
                    activityList: activityList,
                    userType: userType
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.onLoad()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    reloadPage() {
        this.onLoad()
    },

    sumPrice(idList) {
        let totalPrice = 0
        let dPrice = 0
        const thisOrder = []
        idList.map((item) => {
            const that = this
            const productId = item.split("-")[0]
            const spec = item.split("-")[1]
            const cList = this.data.cart.filter(item => item.specId === parseInt(spec))
            const aList = this.data.activityList.filter((item => item.contrastType === "商品" && item.contrastId === parseInt(productId)))
            if (cList.length > 0) {
                console.log(cList[0])
                let thisTimePrice = 0
                if (this.data.userType === 1) {
                    thisTimePrice = cList[0]["count"] * cList[0]["tradePrice"]
                } else {
                    thisTimePrice = cList[0]["count"] * cList[0]["price"]
                }
                let discountPrice = 0
                aList.forEach(r => {
                    if (r.activityType === "满减") {
                        if (thisTimePrice >= r.minPrice && discountPrice < r.activity) {
                            discountPrice = r.activity
                        }
                    } else if (r.activityType === "买赠" && cList[0]["count"] >= r.minPrice) {
                        let dPrice = 0
                        if (this.data.userType === 1) {
                            dPrice = r.activity * cList[0]["tradePrice"]
                        } else {
                            dPrice = r.activity * cList[0]["price"]
                        }
                        if (dPrice > discountPrice) {
                            discountPrice = dPrice
                        }
                    } else if (r.activityType === "折扣") {
                        if (thisTimePrice >= r.minPrice && discountPrice < ((10 - r.activity) * thisTimePrice / 10)) {
                            discountPrice = (((10 - r.activity) * thisTimePrice / 10))
                        }
                    }
                })
                thisOrder.push({
                    openId: that.data.openId,
                    productId: cList[0].productId,
                    specId: cList[0].specId,
                    count: cList[0].count,
                    title: cList[0].title,
                    specName: cList[0].specName,
                    imageUrl: cList[0].imageUrl,
                    dPrice: discountPrice,
                    price: thisTimePrice - discountPrice
                })
                dPrice += discountPrice
                totalPrice += thisTimePrice
            }
        })
        console.log(thisOrder)
        wx.setStorageSync('order', thisOrder)
        this.setData({
            price: totalPrice - dPrice,
            discount: dPrice,
        })
    },

    //结算
    toSettlement() {
        if (this.data.PSId.length > 0) {
            wx.navigateTo({
                url: "../settlementPage/index"
            })
        } else {
            wx.showToast({
                title: '您还没有选择商品！',
                icon: 'none',
                duration: 2000
            })
        }
    },

    //删除
    delCart() {
        wx.request({
            url: 'https://mbp.jyccloud.cn/mbp/deleteCart',
            method: 'post',
            data: JSON.stringify({
                openId: this.data.openId,
                PSId: this.data.PSId
            }),
            success: (res) => {
                try {
                    wx.setStorageSync('cart', res.data)
                } catch (e) {
                    console.warn(e)
                } finally {
                    this.onLoad()
                }
            }
        })
    },

    // 单选
    checkboxChange: function (e) {
        let id = e.detail.value
        this.sumPrice(e.detail.value)
        let cart = this.data.cart
        if (id.length === cart.length) {
            this.setData({
                allChecked: true
            })
        } else {
            this.setData({
                allChecked: false
            })
        }
        const newCart = cart.map(r => {
            if (id.indexOf(r.productId + "-" + r.specId) === -1) {
                r["checked"] = false
            } else {
                r["checked"] = true
            }
            return r
        })
        this.setData({
            PSId: id,
            cart: newCart
        })
    },

    // 全选
    checkAll: function (e) {
        const c = !this.data.allChecked
        const cart = this.data.cart
        const id = []
        const newCart = cart.map(r => {
            if (c) {
                id.push(r.productId + "-" + r.specId)
                r["checked"] = true
            } else {
                r["checked"] = false
            }
            return r
        })
        this.sumPrice(id)
        this.setData({
            PSId: id,
            cart: newCart,
            allChecked: c
        })
    },
})